<template>
  <div class="car-list">
    <div class="header"><h2>违章记录</h2><div class="actions"><button class="primary" @click="openCreate">新增</button></div></div>
    <div class="toolbar">
      <input v-model.trim="query.man" placeholder="违章人(模糊)" @keyup.enter="load" />
      <input type="date" v-model="query.date" />
      <input v-model.trim="query.licensePlateNumber" placeholder="车牌号" @keyup.enter="load" />
      <button @click="onSearch">查询</button>
      <button class="plain" @click="onReset">重置</button>
    </div>

    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>编号</th>
          <th>标题</th>
          <th>违章人</th>
          <th>日期</th>
          <th>车牌</th>
          <th>处理结果</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="r in list" :key="r.BreakRulesAndRegulationsId">
          <td>{{ r.BreakRulesAndRegulationsId }}</td>
          <td>{{ r.BreakRulesAndRegulationsCode }}</td>
          <td>{{ r.BreakRulesAndRegulationsTitle }}</td>
          <td>{{ r.BreakRulesAndRegulationsMan }}</td>
          <td>{{ formatDate(r.BreakRulesAndRegulationsDate) }}</td>
          <td>{{ r.LicensePlateNumber || '-' }}</td>
          <td>{{ r.BreakRulesAndRegulationsMessage || '-' }}</td>
          <td>
            <button @click="onView(r)">查看</button>
            <button @click="edit(r)" class="plain">编辑</button>
            <button @click="onDelete(r)" class="danger">删除</button>
          </td>
        </tr>
        <tr v-if="!loading && list.length===0">
          <td colspan="8" class="empty">暂无数据</td>
        </tr>
      </tbody>
    </table>

    <div class="pagination">
      <div class="page-size">
        <span>每页</span>
        <div class="page-size-group">
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 10 }" @click="setPageSize(10)">10</button>
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 20 }" @click="setPageSize(20)">20</button>
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 50 }" @click="setPageSize(50)">50</button>
        </div>
      </div>
      <div class="pager-controls">
        <button :disabled="page===1" @click="prev">上一页</button>
        <span>第 {{ page }} / {{ totalPage }} 页</span>
        <button :disabled="page>=totalPage" @click="next">下一页</button>
      </div>
    </div>
    <!-- 弹窗：新增/编辑 -->
    <div v-if="showModal" class="modal-mask">
      <div class="modal">
        <div class="modal-header">
          <div>{{ isEdit ? '编辑违章记录' : '新增违章记录' }}</div>
          <button class="modal-close" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <div class="form-item"><label class="label">车牌</label><input class="input" v-model.trim="form.LicensePlateNumber" /></div>
            <div class="form-item"><label class="label">违章时间</label><input class="input" type="date" v-model="dateInput" /></div>
            <div class="form-item"><label class="label">违章地点</label><input class="input" v-model.trim="form.BreakRulesLocation" /></div>
            <div class="form-item"><label class="label">违章类型</label><input class="input" v-model.trim="form.BreakRulesType" /></div>
            <div class="form-item"><label class="label">罚款金额</label><input class="input" type="number" v-model.number="form.FineAmount" /></div>
            <div class="form-item"><label class="label">扣分</label><input class="input" type="number" v-model.number="form.DeductPoints" /></div>
            <div class="form-item"><label class="label">备注</label><input class="input" v-model.trim="form.Remarks" /></div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn" @click="closeModal">取消</button>
          <button class="btn primary" :disabled="submitting" @click="submit">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { carServicesApi } from '@/api'

type BreakRules = {
  BreakRulesAndRegulationsId: number
  BreakRulesAndRegulationsCode?: string
  BreakRulesAndRegulationsTitle?: string
  LicensePlateNumber?: string
  BreakRulesAndRegulationsMan?: string
  BreakRulesAndRegulationsDate?: string
  BreakRulesAndRegulationsMessage?: string
}

const list = ref<BreakRules[]>([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const totalPage = ref(1)

const query = reactive({
  man: '',
  date: '',
  licensePlateNumber: ''
})

async function load() {
  loading.value = true
  try {
    const params: any = { Pageindex: page.value, PageSize: pageSize.value }
    if (query.man) params.BreakRulesAndRegulationsMan = query.man
    if (query.date) params.BreakRulesAndRegulationsDate = query.date
    if (query.licensePlateNumber) params.LicensePlateNumber = query.licensePlateNumber

    const res = await carServicesApi.getBreakRulesList(params)
    const container: any = (res && (res as any).data) ? (res as any).data : res
    const dataList = Array.isArray(container?.data) ? container.data : (Array.isArray(container?.Data) ? container.Data : [])
    list.value = dataList || []
    const totalCount = container?.TotalCount ?? dataList?.length ?? 0
    totalPage.value = container?.TotalPage ?? Math.max(1, Math.ceil((Number(totalCount)||0)/pageSize.value))
  } catch (err) {
    console.error('加载违章记录失败:', err)
    list.value = []
  } finally {
    loading.value = false
  }
}

function onSearch() { page.value = 1; load() }
function onReset() { query.man=''; query.date=''; query.licensePlateNumber=''; page.value=1; load() }
function prev() { if (page.value>1){ page.value--; load() }}
function next() { if (page.value<totalPage.value){ page.value++; load() }}
function setPageSize(size:number){ if(pageSize.value!==size){ pageSize.value=size; page.value=1; load() }}

function onView(r: BreakRules){ carServicesApi.getBreakRulesDetail({ Id: r.BreakRulesAndRegulationsId }) }
async function onDelete(r: BreakRules){ await carServicesApi.deleteBreakRules?.({ Id: r.BreakRulesAndRegulationsId }) ; load() }

// 弹窗表单
const showModal = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const form = reactive<any>({
  BreakRulesAndRegulationsId: 0,
  LicensePlateNumber: '',
  BreakRulesLocation: '',
  BreakRulesType: '',
  FineAmount: undefined,
  DeductPoints: undefined,
  Remarks: ''
})
const dateInput = ref('')
function openCreate(){ isEdit.value=false; Object.assign(form,{BreakRulesAndRegulationsId:0,LicensePlateNumber:'',BreakRulesLocation:'',BreakRulesType:'',FineAmount:undefined,DeductPoints:undefined,Remarks:''}); dateInput.value=''; showModal.value=true }
function edit(r: BreakRules){ isEdit.value=true; Object.assign(form,r); dateInput.value = r.BreakRulesAndRegulationsDate? formatDateInput(r.BreakRulesAndRegulationsDate):''; showModal.value=true }
function closeModal(){ showModal.value=false }
function formatDateInput(s: string){ const d=new Date(s); if(Number.isNaN(d.getTime())) return ''; const m=String(d.getMonth()+1).padStart(2,'0'); const day=String(d.getDate()).padStart(2,'0'); return `${d.getFullYear()}-${m}-${day}` }
async function submit(){
  if(!form.LicensePlateNumber || !dateInput.value) return
  submitting.value = true
  try{
    if(isEdit.value && form.BreakRulesAndRegulationsId){
      await carServicesApi.updateBreakRules({
        BreakRulesAndRegulationsId: form.BreakRulesAndRegulationsId,
        LicensePlateNumber: form.LicensePlateNumber,
        BreakRulesTime: new Date(`${dateInput.value}T00:00:00`).toISOString(),
        BreakRulesLocation: form.BreakRulesLocation || undefined,
        BreakRulesType: form.BreakRulesType || undefined,
        FineAmount: form.FineAmount,
        DeductPoints: form.DeductPoints,
        HandlingStatus: undefined,
        Remarks: form.Remarks || undefined,
        LastModifiedBy: localStorage.getItem('username') || 'web-user'
      })
    }else{
      await carServicesApi.createBreakRules({
        LicensePlateNumber: form.LicensePlateNumber,
        BreakRulesTime: new Date(`${dateInput.value}T00:00:00`).toISOString(),
        BreakRulesLocation: form.BreakRulesLocation || undefined,
        BreakRulesType: form.BreakRulesType || undefined,
        FineAmount: form.FineAmount,
        DeductPoints: form.DeductPoints,
        HandlingStatus: undefined,
        Remarks: form.Remarks || undefined,
        CreatedBy: localStorage.getItem('username') || 'web-user'
      })
    }
    showModal.value=false; page.value=1; await load()
  } finally { submitting.value=false }
}

function formatDate(s?: string){ if(!s) return '-'; const d=new Date(s); return d.toLocaleDateString('zh-CN') }

onMounted(load)
</script>

<style scoped>
.car-list{ padding:16px; }
.toolbar{ display:flex; gap:8px; align-items:center; margin-bottom:12px; }
.table{ width:100%; border-collapse:collapse; background:#fff; }
.table th,.table td{ border:1px solid #eaeaea; padding:8px; text-align:left; }
.empty{ text-align:center; color:#909399; }
.header{ display:flex; align-items:center; justify-content:space-between; margin-bottom:10px; }
.actions{ display:flex; gap:8px; }
.modal-mask{ position:fixed; inset:0; background:rgba(0,0,0,.35); display:flex; align-items:center; justify-content:center; z-index:999; }
.modal{ width:560px; background:#fff; border-radius:6px; overflow:hidden; box-shadow:0 10px 30px rgba(0,0,0,.2); }
.modal-header{ display:flex; align-items:center; justify-content:space-between; padding:12px 14px; background:#f7f8fa; border-bottom:1px solid #ebeef5; }
.modal-close{ border:none; background:transparent; font-size:18px; cursor:pointer; }
.modal-body{ padding:12px 14px; }
.modal-footer{ padding:10px 14px; text-align:right; border-top:1px solid #ebeef5; }
.btn{ height:32px; padding:0 16px; border:1px solid #dcdfe6; background:#fff; border-radius:4px; cursor:pointer; }
.btn.primary{ background:#409eff; border-color:#409eff; color:#fff; }
.form-grid{ display:grid; grid-template-columns: repeat(2, 1fr); gap:12px 16px; }
.form-item{ display:flex; align-items:center; gap:8px; }
.label{ width:90px; color:#666; }
.input{ flex:1; height:32px; line-height:32px; border:1px solid #dcdfe6; border-radius:4px; padding:0 10px; }
.pagination{ display:flex; justify-content:space-between; align-items:center; margin-top:12px; }
.page-size-group{ display:inline-flex; background:#f0f2f5; border:1px solid #d9d9d9; border-radius:999px; padding:2px; }
.page-size-pill{ border:none; background:transparent; padding:6px 12px; border-radius:999px; cursor:pointer; font-size:12px; color:#606266; }
.page-size-pill.active{ background:#fff; color:#303133; border:1px solid #d9d9d9; }
.pager-controls{ display:flex; align-items:center; gap:10px; }
button{ padding:6px 12px; border:1px solid #dcdfe6; background:#fff; border-radius:4px; cursor:pointer; }
button.plain{ background:transparent; border:1px solid #ccc; }
button.primary{ background:#409eff; color:#fff; border-color:#409eff; }
button.danger{ color:#f56c6c; border-color:#f56c6c; }
</style>


